package review;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-08-05
 * Time: 18:32
 */
public class EchoServer {
    //先打开socket文件
    DatagramSocket socket = null;
    public EchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        while(true) {
            //1.接收客户端请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //2.解析请求
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //3.响应
            String response = process(request);
            //4.将响应返回的字符串解析发送会客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),request.getBytes().length,requestPacket.getSocketAddress());
            //5.发送
            socket.send(responsePacket);
            System.out.printf("[%s:%d] request:%s  response:%s",requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(8000);
        server.start();
    }
}
